package com.hyj.util;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/*
 * 彩讯科技平台开发部
 * GZIP压缩工具类
 * @author huyj
 * 修改记录：
 *  1 2012年8月13日 huyajun 创建
 * 
 */
public class GzipUtil {
	
	/**
	 * 获取Gzip 输出流
	 * @param out
	 * @return
	 * @throws IOException
	 */
   public static GZIPOutputStream  getGzipOutputStream(OutputStream out) throws IOException{
	   GZIPOutputStream gout  = new GZIPOutputStream(out);
	   return gout;
   }

	
	/**
	 * 数据压缩
	 * @param data
	 * @return
	 */
	public static byte[] dataCompress(byte[] data) {
		GZIPOutputStream gos;
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(data);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			gos = new GZIPOutputStream(baos);
			
			byte[] buf = new byte[1024];
			int num;
			while ((num = bais.read(buf)) != -1) {
				gos.write(buf, 0, num);
			}
			gos.finish();
			gos.flush();
			gos.close();
			byte[] output = baos.toByteArray();  
			return output;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 数据解压缩
	 * @param data
	 * @return
	 */
	public static byte[] dataDecompress(byte[] data){
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(data);
			GZIPInputStream gis = new GZIPInputStream(bais);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int num;
			while((num=gis.read(buf))!=-1){
				baos.write(buf, 0, num);
			}
			gis.close();
			byte[] ret = baos.toByteArray();
			baos.close();
			return ret;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	 

}
